﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.Threading;

using PRET.PRETService.Data;

namespace PRET.PRETService
{
    public partial class PRETService : ServiceBase
    {
        private readonly static string LogSource = "PRETLogService";
        private readonly static string LogName = "PRETLog";
        private static bool IsRunning = false;

        public PRETService()
        {
            InitializeComponent();
            InitializeEventLog();
        }

        private void InitializeEventLog()
        {
            if (!EventLog.SourceExists(LogSource))
                EventLog.CreateEventSource(LogSource, LogName);
            log.Source = LogSource;
            log.Log = LogName;
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                log.WriteEntry("PRET service started");

                // 创建所有表格
                using (ServiceAdapter adapter = new ServiceAdapter(this.log))
                {
                    adapter.CreateAllTablesInDB();
                }

                ThreadPool.QueueUserWorkItem(new WaitCallback(this.InfoCollection));
                //this.OnUpdateOrderFeedback(null, null);

                // 设定10分钟的时间间隔来循环调用OnTimer函数
                int sec = int.Parse(ConfigurationManager.ConnectionStrings["CollectionInterval"].ConnectionString);
                System.Timers.Timer timer1 = new System.Timers.Timer();
                timer1.Interval = sec * 1000;
                timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.OnInfoCollection);
                //timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.OnJHJCollection);
                //timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.OnMeterCollection);
                //timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.OnUpdateOrderFeedback);
                //timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.OnWaitingOrderCollection);
                timer1.Start();
            }
            catch(Exception ex)
            {
                string msg = string.Format("PRETService.OnStart() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        protected override void OnStop()
        {
            log.WriteEntry("PRET service stoped");
        }

        // 收集WINCC里的挤出机信息，并存储到自定义的SQL DB中
        public void OnInfoCollection(object sender, System.Timers.ElapsedEventArgs args)
        {
            while (IsRunning)
            {
                Thread.Sleep(5000);
            }
            IsRunning = true;
            InfoCollection(null);
            DeleteOlderData();
            IsRunning = false;
        }

        private void InfoCollection(Object para)
        {
            try
            {
                using (ServiceAdapter adapter = new ServiceAdapter(this.log))
                {
                    //log.WriteEntry("开始从WINCC中收集挤出机数据");
                    adapter.CollectionJCJData();
                    //adapter.CollectionJCJData2();
                    //log.WriteEntry("完成：从WINCC中收集挤出机数据");

                    //log.WriteEntry("开始从WINCC中收集均化机数据");
                    adapter.CollectionJHJData();
                    //log.WriteEntry("完成：从WINCC中收集均化机数据");

                    //log.WriteEntry("开始从WINCC中收集待产信息数据");
                    adapter.CollectionWaitingOrder();
                    //log.WriteEntry("完成：从WINCC中收集待产信息数据");

                    //log.WriteEntry("开始从WINCC中收集班组工作时间数据");
                    adapter.CollectionTeamWorkTime();
                    //log.WriteEntry("完成：从WINCC中收集班组工作时间数据");

                    //log.WriteEntry("开始从WINCC中收集高低柜数据");
                    adapter.CollectionHighLowData();
                    //log.WriteEntry("完成：从WINCC中收集高低柜数据");

                    //log.WriteEntry("开始从WINCC中收集高低柜电压数据");
                    adapter.CollectionHighLowVoltage();
                    //log.WriteEntry("完成：从WINCC中收集高低柜电压数据");

                    //log.WriteEntry("开始从WINCC中收集温湿度数据");
                    adapter.CollectionHumTemData();
                    //log.WriteEntry("完成：从WINCC中收集温湿度数据");

                    //log.WriteEntry("开始更新滑石母粒机信息到ERP表格中");
                    adapter.CollectionHSMLJData();
                    //log.WriteEntry("完成：更新滑石母粒机信息到ERP表格中");

                    //log.WriteEntry("开始更新订单生产信息到ERP表格中");
                    adapter.UpdateOrderFeedback();
                    //log.WriteEntry("完成：更新订单生产信息到ERP表格中");

                    // 收集生产线效率
                    adapter.CollectionProlineEff();

                    // 收集生产线待机时间
                    adapter.CollectionProlineStandby();

                    // 收集生产任务信息
                    adapter.CollectionProduceTask();
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("PRETService.OnInfoCollection() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }
        private void DeleteOlderData()
        {
            try
            {
                using (ServiceAdapter adapter = new ServiceAdapter(this.log))
                {
                    // TODO: 删除winccSQL里面7天之前的数据
                    //log.WriteEntry("从winccSQL中删除老的数据");
                    adapter.DeleteOlderData();
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("PRETService.DeleteOldData() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }
    }
}
